<template>
  <section class="component resource-tree">
    <el-tree class="resource-tree" :data="treeData" :current-node-key="cureentKey" :props="{label:'name'}" @current-change="onCurrentChange" show-checkbox highlight-current @check="onCheckChange" :default-expanded-keys="['root']" node-key="id" ref="tree">
    </el-tree>
  </section>
</template>

<script lang="ts">
import Vue from "vue";
import { Tree } from "element-ui";
import Component from "vue-class-component";
import DataForm from "~/components/common/data-form.vue";
import DataBox from "~/components/common/data-box.vue";
import { Dependencies } from "~/core/decorator";
import { ResourceService } from "~/services/management-service/resource.service";
import { CommonService } from "~/utils/common.service";
import { Emit, Watch, Model, Prop } from "vue-property-decorator";
import { Getter, State, namespace } from "vuex-class";

const systemModule = namespace('system-manage')

@Component({
  components: {}
})
export default class ResourceTree extends Vue {
  @Dependencies(ResourceService) private resourceService: ResourceService;
  @systemModule.Getter private systemMenus: any[]

  private treeData: any[] = []
  private resourceDataSet: any[] = []

  @Prop()
  private cureentKey: string;

  @Model('check-menu-change')
  private checkedMenuIds;

  @Emit('check-menu-change')
  private emitCheckedMenuIds(value) { }


  @Emit("update:cureentKey")
  private emitCurrentKey(id) { }

  @Watch('checkedMenuIds', { deep: true })
  private onCheckedMenuIdsChange(val) {
    const tree = this.$refs.tree as Tree;
    tree.setCheckedKeys(val)
  }

  private onCurrentChange(data) {
    this.emitCurrentKey(data.id)
  }

  private onCheckChange() {
    const tree = this.$refs.tree as Tree;
    const nodes = tree.getCheckedNodes(false, false)
    this.emitCheckedMenuIds(nodes.map(v => v.id))
  }

  private mounted() {
    const option = {
      keyName: 'id',
      parentKeyName: 'parent',
      sortKey: 'resoSort'
    }

    const tmpTreeData = CommonService.generateTreeData(this.systemMenus, option)
    tmpTreeData.forEach(v => v.parent = 'root')
    const root = [{
      id: 'root',
      parent: null,
      name: '贷后催收管理系统',
      type: 'ROOT',
      sort: 0,
      children: tmpTreeData
    }]
    this.treeData = root
  }

  private getCheckedNodes() {
    const tree = this.$refs.tree as Tree;
    return tree.getCheckedNodes(false, true).map((x) => x.id).filter((v) => v !== 'root')
  }

}
</script>

<style lang="less" scoped>
.component.resource-tree {
  .resource-tree {
    max-height: 500px;
    overflow-y: auto;
  }
}
</style>
